#  Copyright 2008-2012 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

from robot import utils
from robot.common import BaseTestSuite, BaseTestCase
from robot.parsing import TestData
from robot.errors import ExecutionFailed, DataError
from robot.variables import GLOBAL_VARIABLES
from robot.output import LOGGER
from .model import RunnableTestCase , RunnableTestSuite ,RunnableMultiTestSuite 
 

from .fixture import Setup, Teardown
from .keywords import Keywords
from .namespace import Namespace
from .runerrors import SuiteRunErrors, TestRunErrors
from .userkeyword import UserLibrary
from .context import EXECUTION_CONTEXTS
from .defaultvalues import DefaultValues

import MySQLdb as mdb
from pprint import pprint
import sys



def enum(**enums):
    return type('Enum', (), enums)


def get_delim_seprated_list_string(list,delim):
    list_string =""
    for val in list:
            list_string += (str(val))
            list_string += (delim)
            
    list_string = list_string[:-1]        
    return list_string    


def _execute_query_ignore_dup(query):
        print "query " +query 
        con = None
        try:
            con = mdb.connect('127.0.0.1', 'root',
                'root123', 'ctaf1')
            con.autocommit(True)
            cur = con.cursor()
            
            ret = cur.execute(query)
            print "execute query returned " + str(ret)
            
        except mdb.Error as e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            if (1062 != e.args[0]):
                sys.exit(1)
                
        
            
        finally:
            if con:
                con.close()
        print "query " +query + " executed"

def _execute_query(query):
        print "query " +query 
        con = None
        try:
            con = mdb.connect('127.0.0.1', 'root',
                'root123', 'ctaf1')
            con.autocommit(True)
            cur = con.cursor()
            
            ret = cur.execute(query)
            print "execute query returned " + str(ret)
            
        except mdb.Error as e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit(1)
                
        
            
        finally:
            if con:
                con.close()
        print "query " +query + " executed"       
                
def _execute_select_query(query):
        print "select query " +query
        con = None
        try:
            con = mdb.connect('127.0.0.1', 'root',
                'root123', 'ctaf1')
            cur = con.cursor()
            
            cur.execute(query)
            data = cur.fetchone()
            
            print type(data)
            print "select returned " + str(data)
            
#            pprint (vars(self))

            
        except mdb.Error as e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit(1)
            
        
                
        finally:
            if con:
                con.close()
        print "select query " +query + " executed"
        return data
    
    
def _execute_select_all_query(query):
        print "select query " +query
        con = None
        try:
            con = mdb.connect('127.0.0.1', 'root',
                'root123', 'ctaf1')
            cur = con.cursor()
            
            cur.execute(query)
            data = cur.fetchall()
            
            print type(data)
            print "select returned " + str(data)
            
#            pprint (vars(self))

            
        except mdb.Error as e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit(1)
            
        
                
        finally:
            if con:
                con.close()
        print "select query " +query + " executed"
        return data        


            
                
def DBTestSuite(datasources, settings):
    """Creates a runnable test suite from given data sources and settings.

    This is a factory method that returns either :class:`ExtractableTestSuite`
    or :class:`RunnableMultiTestSuite` depending are one or more data sources
    given. This method, and especially the returned suite, is likely to change
    heavily in version 2.8.

    :param datasources: List of paths to read data from. Starting from 2.7.2,
                        a single datasource can also be given as a string.
    :param settings: Execution configuration.
    :type settings: :class:`~robot.conf.settings.RobotSettings`
    :returns: :class:`ExtractableTestSuite`
    """
    if isinstance(datasources, basestring):
        datasources = [datasources]
    datasources = [utils.abspath(path) for path in datasources]
    suite = _get_suite(datasources, settings['SuiteNames'], settings['WarnOnSkipped'])
    suite.set_options(settings)
    _check_suite_contains_tests(suite, settings['RunEmptySuite'])
    return suite

def _get_suite(datasources, include_suites, warn_on_skipped):
    if not datasources:
        raise DataError("No data sources given.")
    if len(datasources) > 1:
        return _get_multisource_suite(datasources, include_suites, warn_on_skipped)
    
#    return ExtractableTestSuite(_parse_suite(datasources[0], include_suites, warn_on_skipped))
#return RunnableTestSuite(_parse_suite(datasources[0], include_suites, warn_on_skipped))
#    return ExtractableTestSuite(RunnableTestSuite(_parse_suite(datasources[0], include_suites, warn_on_skipped)))
    return ExtractableTestSuite(_parse_suite(datasources[0], include_suites, warn_on_skipped))
    

def _parse_suite(path, include_suites, warn_on_skipped):
    try:
        return TestData(source=path, include_suites=include_suites, warn_on_skipped=warn_on_skipped)
    except DataError, err:
        raise DataError("Parsing '%s' failed: %s" % (path, unicode(err)))

def _get_multisource_suite(datasources, include_suites, warn_on_skipped):
    suitedatas = []
    for datasource in datasources:
        try:
            suitedatas.append(_parse_suite(datasource, include_suites, warn_on_skipped))
        except DataError, err:
            LOGGER.warn(err)
    suite = ExtractableMultiTestSuite(suitedatas)
    if suite.get_test_count() == 0:
        raise DataError("Data sources %s contain no test cases."
                        % utils.seq2str(datasources))
    return suite

def _check_suite_contains_tests(suite, run_empty_suites=False):
    suite.filter_empty_suites()
    if not suite.get_test_count() and not run_empty_suites:
        raise DataError("Test suite '%s' contains no test cases." % suite.source)


class ExtractableTestSuite(RunnableTestSuite):
     def __init__(self, data, parent=None, defaults=None):
         print "initing ExtractableTestSuite"
         self.mandatory_metadata_list = ['PID','PDES','CID','CDES','PVER']
         self.optional_metadata_list = ['PDES','CDES','PVERDES']
         
         BaseTestSuite.__init__(self, data.name, data.source, parent)
         self.variables = GLOBAL_VARIABLES.copy()
         self.variables.set_from_variable_table(data.variable_table)
         self.source = data.source
         self.doc = data.setting_table.doc.value
         self.metadata = self._get_metadata(data.setting_table.metadata)
         self.imports = data.imports
         self.user_keywords = UserLibrary(data.keywords)
         self.setup = Setup(data.setting_table.suite_setup.name,
                           data.setting_table.suite_setup.args)
         self.teardown = Teardown(data.setting_table.suite_teardown.name,
                                 data.setting_table.suite_teardown.args)
         defaults = DefaultValues(data.setting_table, defaults)
         for suite in data.children:
            ExtractableTestSuite(suite, parent=self, defaults=defaults)
         for test in data.testcase_table:
            ExtractableTestCase(test, parent=self, defaults=defaults)
         self._exit_on_failure_mode = False
         self._skip_teardowns_on_exit_mode = False
         self._dry_run_mode = False
         self.product_detail_id = 0
         self.input_tag_list_string ="" 
         self.tag_set_id = 0 
         
   

                     
     def _check_mandatory_metadata (self ):

        all_mandatory_params_present = True
        
        for mandatory_metadata in self.mandatory_metadata_list:
            skip_tag = False
            for optional_metadata in self.optional_metadata_list:
                if (optional_metadata == mandatory_metadata ):
                    print "tag " + optional_metadata + " to be skipped"
                    skip_tag = True
                    break
                
#            print self.metadata
            if ( False == skip_tag and False == self.metadata.has_key(mandatory_metadata)):
                print "Mandatory metadata " + mandatory_metadata +"- Not Present"
                all_mandatory_params_present = False
                break
                            
        return all_mandatory_params_present
                
     
         
     
     
     def _extract_suite_data_to_db(self, context,errors):
#        pprint (vars(self))
        if (self._id == "s1"):
            if (False == self._check_mandatory_metadata()):
                print "All mandatory metadata not present"
                sys.exit(1)
                
            else:
                print "else case"
        
                
        return            
        
    
     def _extract_sub_suites(self, context,errors):
        for suite in self.suites:
            suite.extractTestSetToDB(context.output, context ,errors)


     def _extract_tests(self, context,errors):
        executed_tests = []
        for test in self.tests:
            normname = utils.normalize(test.name)
            if normname in executed_tests:
                LOGGER.warn("Multiple test cases with name '%s' executed in "
                            "test suite '%s'" % (test.name, self.longname))
            executed_tests.append(normname)
            test.extract_test_case_to_DB(context, errors)
     
    
     def extractTestSetToDB(self, output, parent=None, errors=None):
        
         if not errors:
            errors = SuiteRunErrors(self._exit_on_failure_mode,
                                    self._skip_teardowns_on_exit_mode)
         context = self._start_run(output, parent, errors)
#         self._run_setup(context ,errors)
#         self._run_sub_suites(context,errors)
         print "starting extractTestDataToDB"   
         self._extract_sub_suites(context,errors)
         print "done self._extract_sub_suites"   
         self._extract_suite_data_to_db (context,errors)
         print "done self._extract_suite_data_to_db"   
#        self._run_tests(context)
         self._extract_tests(context,errors)
         print "done self._extract_tests"   
#        self._report_status(context)
#        self._run_teardown(context)
#        self._end_run(context)
#        self.getMySQLVersion ()
         print "ending extractTestDataToDB"   

     def _start_extracting(self, output, parent, errors):
        if not errors:
            errors = SuiteRunErrors(self._run_mode_exit_on_failure, self._run_mode_skip_teardowns_on_exit)
        self.run_errors = errors
        self.run_errors.start_suite()
        self.status = 'RUNNING'
        self.starttime = utils.get_timestamp()
        parent_vars = parent.context.get_current_vars() if parent else None
        ns = Namespace(self, parent_vars)
        self.context = EXECUTION_CONTEXTS.start_suite(ns, output, self._run_mode_dry_run)
        if not errors.exit:
            ns.handle_imports()
        self._set_variable_dependent_metadata(self.context)
        output.start_suite(self)
        return self.context
    
#     def run(self, output, parent_context=None, errors=None):
#        print "dummy test suite run"
        
     def run_collect_stats(self, output, parent_context=None, errors=None):
        print "ctaf test suite run"
        RunnableTestSuite.run(self,output,parent_context, errors) 
        self._dry_run_mode = True
        output.product_detail_id = 0 
        output.input_tag_list_string = ""
        output.tag_set_id = 0
        output.test_request_id = 0 
        self._dry_run_mode = True
        """default pass"""
        output.test_set_status = 'PASS'  
        print "running test suite over"  
        self._update_test_suite_statsto_DB(output,parent_context, errors) 
        self._update_test_set_stats(output.test_execution_id, output.test_set_status)



     def _update_sub_suite_test_data(self,output, parent_context=None, errors=None):
        for suite in self.suites:
            self._dry_run_mode = True
            suite._update_test_suite_statsto_DB(output,parent_context,errors)

     def _update_test_suite_statsto_DB(self, output, parent_context=None, errors=None):
        
        self._update_sub_suite_test_data(output, parent_context,errors )
        print "updating test suite stats : suite " + str(self.name) + " status :" + str(self.status)
        self._update_test_suite_stats(output)
        if ('PASS' != output.test_set_status):
            output.test_set_status = 'FAILED'
        
         
         

     
            
#     def _update_test_suite_result_details(self, test,output):
#         
#         test_suite_id = test._get_test_suite_id()
#         query = "insert into test_suite_result (test_suite_id , status) values ('%d','%s')"  % (test_suite_id,  self.status )
#         _execute_query(query)

         
     def _generate_input_tag_list_string(self,output):
         #         print "*" *320
#         print output._settings._opts['Include']
         input_tag_list_string =""
         input_tag_list = output._settings._opts['Include']
         input_tag_list.sort()       
         input_tag_list_string = get_delim_seprated_list_string(input_tag_list,"-")  
         print "input tag list string" + input_tag_list_string   
         self.input_tag_list_string = input_tag_list_string
      
     
                         
            
     def _update_test_suite_stats(self,output):
        executed_tests = []
        updated_test_suite_result = False
        for test in self.tests:
            test._dry_run_mode = True
            normname = utils.normalize(test.name)
            if normname in executed_tests:
                LOGGER.warn("Stats of Multiple test cases with name '%s' executed in "
                            "test suite '%s'"% (test.name, self.longname))
            
            
                
            if (0 == output.product_detail_id):
                output.product_detail_id = test._get_product_detail_id()
                output.input_tag_list_string = self._generate_input_tag_list_string(output)
                output.tag_set_id = self._get_tag_set_id(output.product_detail_id, output.input_tag_list_string)
                output.test_request_id = self._get_request_id(output.tag_set_id)
                output.test_execution_id = self._get_test_execution_id(output.test_request_id)
#            if (False == updated_test_suite_result):
#                
#                self._update_test_suite_result_details (output.test_execution_id)
#                """ skip updating test suite data many times"""
#                updated_test_suite_result = True 
#                
            test.update_stats(output)
            
            if (test.status != 'PASS'):
                output.test_set_status = 'FAILED'
            
                       
     def _update_test_set_stats(self, test_execution_id, status):
        print "updating test set stats"
        query = "insert into test_set_result (test_execution_id, status) values ('%d','%s')"  % (test_execution_id,status )
        _execute_query(query)
     
     
     def _get_tag_set_id(self, product_detail_id , tag_list_string):
        print "getting tag set id"
        tag_set_id =0;
        if (None != tag_list_string):
            query = "select tag_set_id from tag_set where product_detail_id = '%d' and tag_list_string = '%s' " % ( product_detail_id , tag_list_string)
        else:
            query = "select tag_set_id from tag_set where product_detail_id = '%d' and tag_set_name = 'all' " % ( product_detail_id )      
        tag_set_id = (_execute_select_query(query))[0]
        print "tag_set_id is %d" % tag_set_id
                                                                                                                                                        
        return tag_set_id       
    
     def _update_test_suite_result_details ():
        print "inserting test suite data testname: " + self.name
        query = "insert into test_suite_result (product_detail_id) values ('%d')"  % (self._get_product_detail_id() )
        _execute_query_ignore_dup(query)
        
     def _get_test_execution_id(self,test_request_id):
         print "getting test execution id"
         query = "insert into test_execution (test_request_id) values ('%d')"  % (test_request_id)
         _execute_query_ignore_dup(query)
        
         test_execution_id =0;
        
         query = "select max(test_execution_id) from test_execution where  test_request_id= '%d' " % (test_request_id )
         test_execution_id = (_execute_select_query(query))[0]
         print "product id is %d" % test_execution_id
                                                                                                                                                                
         return test_execution_id
         
         
     def _get_request_id(self, tag_set_id):
        print "inserting request data " + self.name
        query = "insert into test_request (tag_set_id) values ('%d')"  % (tag_set_id  )
        _execute_query_ignore_dup(query)
        
        request_id =0;
        
        query = "select max(test_request_id) from test_request where tag_set_id = '%d' " % (tag_set_id )
        request_id = (_execute_select_query(query))[0]
        print "product id is %d" % request_id
                                                                                                                                                                
        return request_id


            
class ExtractableMultiTestSuite(RunnableMultiTestSuite):

    def __init__(self ):
        print "inited ExtractableMultiTestSuite "
    
    def run(self, output, parent_context=None, errors=None):
        self._dry_run_mode = False
        print "dummy multi test suite run"
             
class ExtractableTestCase(RunnableTestCase):

    def __init__(self ,tc_data, parent, defaults):
        
        RunnableTestCase.__init__(self, tc_data,parent, defaults)
        
        print "inited ExtractableTestCase " + self.name 

        
                
        self.mandatory_tag_e = enum(PROD_NAME=0,CUST_NAME=1,PROD_VER=2,BUILD_NO=3,TSID=4,TUNGID=5,TSVER=6)
        self.mandatory_tag_prefix_list = ['PROD_NAME','CUST_NAME','PROD_VER','BUILD_NO','TSID','TUNGID','TSVER']
        self.mandatory_tag_dict = {}
        self.optional_tag_dict = {}
        self.other_tag_list =[]
        
        self._print_all_tags()
        self._populate_mandatory_tag_dict()
#        self._populate_optional_tag_dict()
        self.tag_list_string = ""
        
        
#        self._generate_tag_list_string ()
        
#        self._dry_run_mode = True
        
    
    def extract_test_case_to_DB(self, context, parent_errors):
        print "extract  TestCaseToDB results "
        print "*" * 360
         
#        pprint (vars(self))
        
        print "*" * 160
#        print self.mandatory_tag_dict
        
        if (None == self.mandatory_tag_dict):
            print "err: All mandatory params do not exist "
            return
        print "mandatory_tag_dict" 
        print self.mandatory_tag_dict
        print "*" * 160
        
        print "All mandatory params exist " +   str(self.mandatory_tag_dict)
        self._insert_product_to_DB()
        self._insert_customer_to_DB()
        self._insert_product_details_to_DB()
        self._insert_test_suite_to_DB()
        self._insert_test_case_to_DB()
        
        self._populate_other_tags_list()
        self._update_tag_list_string()
        self._insert_tag_set_to_DB("all")
        self._insert_tags_to_DB()
        self._insert_tag_details_to_DB()
        
    
    def _insert_product_to_DB(self):
        print "inserting product data " + self.name
        query = "insert into product (prod_name) values ('%s')"  % (self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.PROD_NAME]] )
        _execute_query_ignore_dup(query)
        
        
    def _insert_customer_to_DB(self):
        print "inserting customer data " + self.name
        query = "insert into customer (cust_name) values ('%s')"  % (self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.CUST_NAME]] )
        _execute_query_ignore_dup(query)
        
    #FIXME join ?
    def _insert_product_details_to_DB(self):
        
        product_id = self._get_product_id()
        print "product id is %d" % product_id
        if (0 <product_id):
        
            cust_id = self._get_cust_id()
            print "cust id is %d" % cust_id
            if (0 <cust_id):
#                version = mdb.escape_string (self.metadata.get(self.mandatory_metadata_list[4]) )
                version = self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.PROD_VER]]
                test_set_version = self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.TSVER]]
                print "inserting product_details data " + self.name
                query = "insert into product_details (prod_id, cust_id , version, test_set_version) values (%d,%d,'%s','%s')"  % (product_id, cust_id, version , test_set_version )
                
#                print "before escape" + query
#                query = str(mdb.escape_string (query))
#                print "after escape" + query
                _execute_query_ignore_dup(query)
            else:
                print "failed to get customer id"
        else:
            print "failed to get product id"
    
    
        
    def _insert_test_suite_to_DB(self):
        print "inserting test suite data testname: " + self.name
        query = "insert into test_suite (test_suite_id_ext,product_detail_id) values ('%s','%s')"  % (self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.TSID]] ,  self._get_product_detail_id() )
        _execute_query_ignore_dup(query)
        
    def _insert_test_case_to_DB(self):
        print "inserting test case data " + self.name
        query = "insert into test_case (test_case_id_ext,test_suite_id , test_case_name) values ('%s' ,'%s' , '%s')"  % (self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.TUNGID]] ,
          self._get_test_suite_id() ,
          str(self.name) )
        _execute_query_ignore_dup(query)
        
    
        
    def _insert_tag_set_to_DB(self,tag_set_name):
        
        print "inserting default tag set %s" % str(self._get_product_detail_id())
        query = "insert into tag_set (tag_set_name , product_detail_id ,added_time, tag_list_string) values ('%s','%s',now(),'%s') ON DUPLICATE KEY UPDATE  tag_list_string = '%s' " % (tag_set_name, self._get_product_detail_id(), self.tag_list_string, self.tag_list_string)
#        query = "insert into tag_set (tag_set_name , product_detail_id , tag_list_string) values ('%s','%s' ,'%s')  " % (tag_set_name, self._get_product_detail_id(), self.tag_list_string)
        _execute_query(query)
    
    
    def _insert_tags_to_DB(self):
        print "inserting tags " + self.name
        product_detail_id = self._get_product_detail_id() 
        
        if (product_detail_id):
            for tag in self.other_tag_list:
                query = "insert into tags (tag,product_detail_id) values ('%s','%d') ON DUPLICATE KEY UPDATE  tag = '%s'"  % (str(tag), product_detail_id , str(tag) )
                _execute_query(query)
        else:
            print "failed to get product detail id"            

    def _insert_tag_details_to_DB(self):
        
        print "inserting tag details %s" % str(self._get_product_detail_id())
        
        product_detail_id = self._get_product_detail_id()
        if (product_detail_id):
            tag_set_id =self._get_tag_set_id("all", product_detail_id) 
            if (tag_set_id):
                for tag in self.tags:
                    tag_prefix = ((str(tag)).partition('-'))[0]
                    if tag_prefix not in self.mandatory_tag_dict.keys():
                        tag_id = self._get_tag_id(tag, product_detail_id)
                        if (tag_id):
                            query = "insert into tag_details (tag_id,tag_set_id) values ('%d','%d')"  % (tag_id,tag_set_id  )
                            _execute_query_ignore_dup(query)
                        else:
                            print "failed to get tag_id "
            else:
                print "failed to get tag set id "
                
        else:
                print "failed to get product_detailid "       
    
#    def _insert_test_request (self):
        
    
    def _get_tag_id(self, tag, product_detail_id):
        tag_id =0;
        query = "select tag_id from tags where tag = '%s' and  product_detail_id = '%d' " % (tag, product_detail_id )
        tag_id = (_execute_select_query(query))[0]
        print "tag id for tag name %s and product_detail id %d is %d" % (tag, product_detail_id, tag_id)
                                                                                                                                                                
        return tag_id
    
    
    def _get_tag_set_id(self, tag_set_name, product_detail_id):
        tag_set_id =0;
        query = "select tag_set_id from tag_set where tag_set_name = '%s' and  product_detail_id = '%d' " % (tag_set_name, product_detail_id )
        tag_set_id = (_execute_select_query(query))[0]
        print "tag set id for tag se name %s and product_detail id %d is %d" % (tag_set_name, product_detail_id, tag_set_id)
                                                                                                                                                                
        return tag_set_id
        
    def _get_test_suite_id(self):
        test_suite_id =0;
        query = "select test_suite_id from test_suite where test_suite_id_ext = '%s' " % (self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.TSID]] )
        test_suite_id = (_execute_select_query(query))[0]
        print "test suite id is %d" % test_suite_id
                                                                                                                                                                
        return test_suite_id
    
    def _get_test_case_id(self):
        test_case_id =0;
        query = "select test_case_id from test_case where test_case_id_ext = '%s' " % (self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.TUNGID]] )
        test_case_id = (_execute_select_query(query))[0]
        print "test case id is %d" % test_case_id
                                                                                                                                                                
        return test_case_id    
        
    
    
    def _get_product_detail_id(self):
        product_details_id =0;
        prod_id = self._get_product_id()
        if (0 < prod_id ):
            cust_id = self._get_cust_id()
            if ( 0 < cust_id ):
                query = "select prod_details_id from product_details where prod_id = '%d' and cust_id = '%d' and version = '%s' and test_set_version = %s" % (prod_id,
                                                                                                                                                              cust_id,
                                                                                                                                                              self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.PROD_VER]] ,
                                                                                                                                                              self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.TSVER]])
                product_details_id = (_execute_select_query(query))[0]
                print "product details id is %d" % product_details_id
            else:
                print "err: failed to get cust id"    
                 
        else:
            print "err: failed to get prod id"
                                                                                                                                                                
        return product_details_id
            
        
    def _get_product_id(self):
        product_id =0;
        
        query = "select prod_id from product where prod_name = '%s' " % (self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.PROD_NAME]] )
        product_id = (_execute_select_query(query))[0]
        print "product id is %d" % product_id
                                                                                                                                                                
        return product_id
    
    def _get_cust_id(self):
        cust_id =0;
        
        query = "select cust_id from customer where cust_name = '%s' " % (self.mandatory_tag_dict[self.mandatory_tag_prefix_list[self.mandatory_tag_e.CUST_NAME]] )
        cust_id = (_execute_select_query(query))[0]
        print "customer id is %d" % cust_id
                                                                                                                                                                
        return cust_id

    
    def _populate_mandatory_tag_dict (self ):
        
        for mandatory_tag_prefix in self.mandatory_tag_prefix_list:
             print "mandatory_tag_prefix" +mandatory_tag_prefix
             print "self.mandatory_tag_prefix_list" 
             print self.mandatory_tag_prefix_list
             if ( True != self._check_tuple_tag_exists (mandatory_tag_prefix)):
                 print "err: mandatory Param prefix " +  mandatory_tag_prefix + " doesnt exist"
                 self.mandatory_tag_dict = None
                 break
             print "all tags"
             print self.mandatory_tag_dict
             print "self._get_value_for_tag(mandatory_tag_prefix)"
             print str(self._get_value_for_tag(mandatory_tag_prefix))
                      
             self.mandatory_tag_dict[mandatory_tag_prefix] = self._get_value_for_tag(mandatory_tag_prefix)
              
#        print self.mandatory_tag_dict[mandatory_tag_prefix]
#        print self._get_value_for_tag(mandatory_tag_prefix)
          
#    def _populate_optional_tag_dict (self ):
#
#        for tag in self.tags:
#             if ( True != self._check_tuple_tag_exists (mandatory_tag_prefix)):
##                 print "mandatory Param prefix " +  mandatoryTagPrefix + " doesnt exist"
#                 self.mandatory_tag_dict = None
#                 break
#             self.mandatory_tag_dict[mandatory_tag_prefix] = self._get_value_for_tag(mandatory_tag_prefix) 

    def _populate_other_tags_list (self ):    
        print "populating other tags list" + self.name
        for tag in self.tags:
            tag_prefix = ((str(tag)).partition('-'))[0]
            if tag_prefix not in self.mandatory_tag_dict.keys():
                self.other_tag_list.append(tag)
        self.other_tag_list.sort()  
             

    def _update_tag_list_string(self):
        
        tag_list = self._get_existing_tag_list ()
        
        self.other_tag_list += tag_list
        self.other_tag_list = list(set(self.other_tag_list))
        
        self.tag_list_string = get_delim_seprated_list_string(self.other_tag_list,"-")
        
        print "tag list string is " +   self.tag_list_string
                   
    def _get_existing_tag_list (self):
        tag_list = []
        product_detail_id = self._get_product_detail_id()
        query = "select tag from tags where product_detail_id = '%d'" % (product_detail_id)
        tag_list_tuple = _execute_select_all_query(query)
        for tag in tag_list_tuple:
            tag_list.append(tag[0])
        print "existing tag list "
        tag_list.sort()
        print tag_list
        return tag_list
    
    def _print_all_tags (self):
        print "printing all tags "
        for tag in self.tags:
            tagstr = str(tag)
            print (tagstr)
        
    def _check_tuple_tag_exists (self, tag_prefix):
        found_tag = False
        for tag in self.tags:
            tagstr = str(tag)
            split_tuple = tagstr.partition('-')
#            print tagstr + " partitioned to "+  str(split_tuple)
            if( (tag_prefix == str(split_tuple[0]) and (0 < len(str(split_tuple[2]) )))):
                    print "tag " + tag_prefix + " has value " + str(split_tuple[2])
                    found_tag =True
                    break;
        return found_tag       
                    
    def _check_mandatory_tags (self ):

        all_mandatory_params_present = True
        for mandatoryTagPrefix in self.mandatory_tag_prefix_list:
            if ( True != self._check_tuple_tag_exists (mandatoryTagPrefix)):
#                print "MandatoryParam " + mandatoryTagPrefix +"- Not Present"
                all_mandatory_params_present = False
                            
        return all_mandatory_params_present
    
     
                    
    def _get_value_for_tag (self, tag_prefix):
        
        tag_suffix = None
        for tag in self.tags:
            print "tagname" + tag
            tagstr = str(tag)
            split_tuple = tagstr.partition('-')
#            print tagstr + " partitioned to "+  str(split_tuple)
            if( (tag_prefix == str(split_tuple[0]) and (0 < len(str(split_tuple[2]))))):
                    print "getting tag " + tag_prefix + " with value" + str(split_tuple[2])
                    tag_suffix = str(split_tuple[2])
                    break 
                
        return tag_suffix 
    
    
    def _get_key_value_tuple (self, str,delim='-'):
        return str.partition(delim)




#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#test results

    def update_stats(self,output):
        print "test status of test: " + str(self.name) + " is " +str(self.status)
#        _update_test_set_result_details()
#        _update_test_suite_result_details()
        self._update_test_case_result_details(output)
        

        
    def _update_test_set_result_details (self):
        print "inserting test suite data testname: " + self.name
        query = "insert into test_set_result (product_detail_id) values ('%d')"  % (self._get_product_detail_id() )
        _execute_query_ignore_dup(query)
        
        
        
    
                
            
    def _update_test_case_result_details (self,output):
        print "inserting test case  result data testname: " + self.name
        query = "insert into test_case_result (test_case_id , status , test_execution_id) values ('%d','%s', '%d')"  % (self._get_test_case_id(),  self.status ,output.test_execution_id)
        _execute_query_ignore_dup(query)     
           
    def _update_test_case_stats(self):
        print "test status of test: " + str(self.name) + " is " +str(self.status)
                
   
        
        
        
             
            
        
    